<template>
  <div class="params">
    <!-- 面包屑导航 -->
    <breadcrumb firstTitle="商品管理" secondTitle="参数列表"></breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false">
      </el-alert>
      <el-row>
        <el-col>
          选择商品分类：
          <el-cascader v-model="selectId" :options="cartList" @change="handleCasChange" :props="cartParamProps"></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many" ref="">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数</el-button>

          <!-- 表格视图 -->
          <el-table :data="manyTableData" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope.row)">{{ item }}</el-tag>
                <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditorDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>

          <!-- 表格视图 -->
          <el-table :data="onlyTableData" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{ item }}</el-tag>
                <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditorDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog :title="textTitle" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数dialog 参数对话框 -->
    <el-dialog :title="'修改' + textTitle" :visible.sync="editorVisible" width="50%" @close="closeEditorDialog">
      <el-form :model="editorForm" :rules="editFormRules" ref="editorFormRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editorForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editorVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '../../network/request'
import breadcrumb from '../breadcurmb/BreakCrumb.vue'
import { paramsFormRulesMixin } from '@/common/mixin'

export default {
  name: 'MyParams',
  mixins: [paramsFormRulesMixin],
  created() {
    this.getCartList()
  },
  computed: {
    // 控制添加属性按钮的是否禁用
    isBtnDisabled() {
      return !(this.selectId.length === 3)
    },
    // 获取级联选择器的三级分类的id
    isSelectId() {
      return this.selectId[this.selectId.length - 1]
    },
    // 动态判断dialog 上面显示上面什么样的的title
    textTitle() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  data() {
    return {
      // 商品分类列表
      cartList: [],
      // cascader 级联选择器 储存选中值的id
      selectId: [],
      cartParamProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // Tab标签默认活跃的页签
      activeName: 'many',
      // 动态属性  表格的数据
      manyTableData: [],
      // 静态属性  表格的属性
      onlyTableData: [],
      // 控制dialog对话框的显示与隐藏
      addDialogVisible: false,
      // dialog表单中数据
      addForm: {
        attr_name: ''
      },
      // addFormRules: {
      //   attr_name: [
      //     {
      //       required: true,
      //       message: '请输入参数名称',
      //       trigger: 'blur'
      //     }
      //   ]
      // },
      // 控制编辑参数对话框的显示与隐藏
      editorVisible: false,
      // 编辑dialog表单中的值
      editorForm: {
        attr_name: ''
      }
      // editorFormRules: {
      //   attr_name: [
      //     {
      //       required: true,
      //       message: '请输入参数名称',
      //       trigger: 'blur'
      //     }
      //   ]
      // }
    }
  },
  methods: {
    async getCartList() {
      const { data: res } = await request('categories', {
        type: 3
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.cartList = res.data
    },
    // 点击tab栏切换时触发
    handleTabClick() {
      this.handleCasChange()
    },
    // 当级联选择器 选中的值发生改变时触发
    async handleCasChange() {
      const { data: res } = await request(`categories/${this.isSelectId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品参数列表失败')

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 给每一行添加inputVisible属性  用来控制tag标签后面的表单的显示与隐藏
        // item.inputVisible = false
        // tag标签 后面表单里面的值
        // item.inputValue = ''
        this.$nextTick(() => {
          this.$set(item, 'inputVisible', false)
          this.$set(item, 'inputValue', '')
        })
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 关闭dialog对话框时触发
    closeAddDialog() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击dialog里面的确认按钮
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await request.post(`categories/${this.isSelectId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加商品参数或静态属性失败')

        // 重现渲染页面数据
        this.handleCasChange()
        this.addDialogVisible = false
      })
    },
    // 关闭编辑dialog
    closeEditorDialog() {
      this.$refs.editorFormRef.resetFields()
    },
    // 修改表单参数
    editorParams() {
      this.$refs.editorFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await request.put(`categories/${this.isSelectId}/attributes/${this.editorForm.attr_id}`, {
          attr_name: this.editorForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('编辑参数失败')

        this.$message.success('修改参数成功！')
        // 重新渲染参数列表数据
        this.handleCasChange()
        this.editorVisible = false
      })
    },
    // 点击展示编辑对话框
    async showEditorDialog(id) {
      const { data: res } = await request(`categories/${this.selectId}/attributes/${id}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
      this.editorForm = res.data

      this.editorVisible = true
    },
    // 点击删除商品参数
    async removeParams(val) {
      const resultConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (resultConfirm !== 'confirm') return this.$message.info('取消删除商品参数')

      const { data: res } = await request.delete(`categories/${this.isSelectId}/attributes/${val.attr_id}`)
      if (res.meta.status !== 200) return this.$message.error('删除商品参数失败！')
      this.$message.success('删除商品参数成功！')

      // 重新获取商品参数列表
      this.handleCasChange()
    },
    // 按下回车键 失去表单焦点时触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAtrribute(row)
    },
    // tag失去焦点触发
    // async handleInputConfirm2(row) {
    //   if (row.inputValue.trim().length === 0) {
    //     row.inputVisible = false
    //     row.inputValue = ''
    //   }
    //   this.saveAtrribute(row)
    // },
    async saveAtrribute(row) {
      const { data: res } = await request.put(`categories/${this.isSelectId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // 将数组切割成字符串
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('编辑参数失败')
      this.$message.success('编辑参数成功！')
      row.inputVisible = false
    },
    // 展示tag标签后面的按钮
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 点击删除tag
    handleClose(index, row) {
      // 会改变原数组  将数组转换成字符串
      row.attr_vals.splice(index, 1)
      this.saveAtrribute(row)
    }
  },
  components: {
    breadcrumb
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin: 20px 0;
}
.el-tag {
  margin: 10px 25px;
}
.el-input {
  width: 120px;
}
.el-form .el-input {
  width: 100%;
}
</style>